<template>
  <div class="favorites-page">
    <div class="container">
      <div class="page-header">
        <h1>我的收藏</h1>
        <div class="favorites-actions">
          <el-button @click="clearAllFavorites" :disabled="favorites.length === 0">
            <el-icon><Delete /></el-icon>
            清空收藏
          </el-button>
        </div>
      </div>

      <div class="favorites-content" v-loading="loading">
        <!-- 收藏列表 -->
        <div v-if="favorites.length > 0" class="favorites-list">
          <div class="view-controls">
            <div class="view-toggle">
              <el-button-group>
                <el-button :type="viewMode === 'grid' ? 'primary' : ''" @click="viewMode = 'grid'">
                  <el-icon><Grid /></el-icon>
                </el-button>
                <el-button :type="viewMode === 'list' ? 'primary' : ''" @click="viewMode = 'list'">
                  <el-icon><List /></el-icon>
                </el-button>
              </el-button-group>
            </div>
            <div class="sort-controls">
              <el-select v-model="sortBy" placeholder="排序方式" @change="handleSort">
                <el-option label="按收藏时间" value="favoriteTime" />
                <el-option label="按价格从低到高" value="priceAsc" />
                <el-option label="按价格从高到低" value="priceDesc" />
                <el-option label="按评分从高到低" value="ratingDesc" />
              </el-select>
            </div>
          </div>

          <!-- 网格视图 -->
          <div v-if="viewMode === 'grid'" class="favorites-grid">
            <div
              v-for="favorite in sortedFavorites"
              :key="favorite.id"
              class="favorite-card"
              @click="$router.push(`/property/${favorite.propertyId}`)"
            >
              <div class="property-image">
                <img :src="favorite.property?.imageUrl || 'https://images.unsplash.com/photo-1566073771259-6a8506099945?w=400&h=300&fit=crop'" :alt="favorite.property?.title || '民宿'" />
                <div class="property-badge" v-if="favorite.property?.isHot">热门</div>
                <div class="favorite-actions">
                  <el-button
                    circle
                    size="small"
                    @click.stop="removeFavorite(favorite.propertyId)"
                    class="remove-btn"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
              <div class="property-info">
                <h3>{{ favorite.property?.title || '民宿房源' }}</h3>
                <p class="property-location">
                  <el-icon><Location /></el-icon>
                  {{ favorite.property?.city || '位置信息' }} · {{ favorite.property?.address || '' }}
                </p>
                <div class="property-rating" v-if="favorite.property?.rating">
                  <el-rate v-model="favorite.property.rating" disabled show-score />
                  <span class="review-count">({{ favorite.property?.reviewCount || 0 }}条评价)</span>
                </div>
                <div class="property-amenities" v-if="favorite.property?.amenities && favorite.property.amenities.length > 0">
                  <el-tag v-for="amenity in favorite.property.amenities" :key="amenity" size="small">
                    {{ amenity }}
                  </el-tag>
                </div>
                <div class="property-price">
                  <span class="price">¥{{ favorite.property?.basePrice || 0 }}</span>
                  <span class="unit">/晚</span>
                </div>
                <div class="favorite-time">
                  收藏于 {{ formatDate(favorite.createdAt) }}
                </div>
              </div>
            </div>
          </div>

          <!-- 列表视图 -->
          <div v-else class="favorites-list-view">
            <div
              v-for="favorite in sortedFavorites"
              :key="favorite.id"
              class="favorite-list-item"
              @click="$router.push(`/property/${favorite.propertyId}`)"
            >
              <div class="property-image">
                <img :src="favorite.property?.imageUrl || 'https://images.unsplash.com/photo-1566073771259-6a8506099945?w=400&h=300&fit=crop'" :alt="favorite.property?.title || '民宿'" />
                <div class="property-badge" v-if="favorite.property?.isHot">热门</div>
              </div>
              <div class="property-content">
                <div class="property-header">
                  <h3>{{ favorite.property?.title || '民宿房源' }}</h3>
                  <div class="favorite-actions">
                    <el-button
                      text
                      @click.stop="removeFavorite(favorite.propertyId)"
                      class="remove-btn"
                    >
                      <el-icon><Delete /></el-icon>
                      移除收藏
                    </el-button>
                  </div>
                </div>
                <p class="property-location">
                  <el-icon><Location /></el-icon>
                  {{ favorite.property?.city || '位置信息' }} · {{ favorite.property?.address || '' }}
                </p>
                <div class="property-rating" v-if="favorite.property?.rating">
                  <el-rate v-model="favorite.property.rating" disabled show-score />
                  <span class="review-count">({{ favorite.property?.reviewCount || 0 }}条评价)</span>
                </div>
                <div class="property-amenities" v-if="favorite.property?.amenities && favorite.property.amenities.length > 0">
                  <el-tag v-for="amenity in favorite.property.amenities" :key="amenity" size="small">
                    {{ amenity }}
                  </el-tag>
                </div>
                <div class="property-description">
                  {{ favorite.property?.description || '暂无描述' }}
                </div>
                <div class="favorite-time">
                  收藏于 {{ formatDate(favorite.createdAt) }}
                </div>
              </div>
              <div class="property-price-section">
                <div class="property-price">
                  <span class="price">¥{{ favorite.property?.basePrice || 0 }}</span>
                  <span class="unit">/晚</span>
                </div>
                <el-button type="primary" @click.stop="$router.push(`/booking/${favorite.propertyId}`)">
                  立即预订
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-state">
          <el-empty description="暂无收藏的房源">
            <el-button type="primary" @click="$router.push('/search')">
              去发现房源
            </el-button>
          </el-empty>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getFavorites, cancelFavorite } from '../../api/favorites'
import request from '../../api/request'

const router = useRouter()

// 视图模式
const viewMode = ref('grid')

// 排序方式
const sortBy = ref('favoriteTime')

// 加载状态
const loading = ref(false)

// 收藏数据（包含房产详情）
const favorites = ref([])

// 排序后的收藏列表
const sortedFavorites = computed(() => {
  const sorted = [...favorites.value]
  
  switch (sortBy.value) {
    case 'favoriteTime':
      return sorted.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
    case 'priceAsc':
      return sorted.sort((a, b) => {
        const priceA = a.property?.basePrice || 0
        const priceB = b.property?.basePrice || 0
        return priceA - priceB
      })
    case 'priceDesc':
      return sorted.sort((a, b) => {
        const priceA = a.property?.basePrice || 0
        const priceB = b.property?.basePrice || 0
        return priceB - priceA
      })
    case 'ratingDesc':
      return sorted.sort((a, b) => {
        const ratingA = a.property?.rating || 0
        const ratingB = b.property?.rating || 0
        return ratingB - ratingA
      })
    default:
      return sorted
  }
})

// 加载收藏数据
const loadFavorites = async () => {
  try {
    loading.value = true
    const response = await getFavorites()
    
    // 如果后端返回的是数组，直接使用；如果包装在data中，则取data
    const favoritesList = Array.isArray(response) ? response : (response.data || [])
    
    console.log('收藏列表:', favoritesList)
    
    // 为每个收藏项加载房产详情和评论统计
    const favoritesWithDetails = await Promise.all(
      favoritesList.map(async (favorite) => {
        try {
          // 1. 获取房源基本信息
          const propertyResponse = await request.get(`/api/properties/${favorite.propertyId}`).catch(() => null)
          
          // 2. 获取该房源的所有评论
          const reviewsResponse = await request.get(`/api/reviews/findByPropertyId?propertyId=${favorite.propertyId}`).catch(() => null)
          
          let property = null
          if (propertyResponse) {
            const propertyData = propertyResponse.data || propertyResponse
            
            // 3. 计算评分和评论数
            let reviewCount = 0
            let avgRating = 0
            
            if (reviewsResponse) {
              const reviews = Array.isArray(reviewsResponse) ? reviewsResponse : (reviewsResponse.data || [])
              reviewCount = reviews.length
              
              if (reviewCount > 0) {
                const totalRating = reviews.reduce((sum, r) => sum + (r.rating || 0), 0)
                avgRating = Math.round((totalRating / reviewCount) * 10) / 10
              }
            }
            
            property = {
              id: propertyData.id,
              title: propertyData.title || '民宿房源',
              city: propertyData.city || '位置信息',
              address: propertyData.address || '',
              basePrice: propertyData.basePrice || 0,
              rating: avgRating,
              reviewCount: reviewCount,
              imageUrl: propertyData.imageUrl || 'https://images.unsplash.com/photo-1566073771259-6a8506099945?w=400&h=300&fit=crop',
              isHot: propertyData.isHot === 1,
              amenities: [],
              description: propertyData.description || '暂无描述'
            }
          } else {
            // 如果获取失败，使用默认数据
            property = {
              id: favorite.propertyId,
              title: '民宿房源',
              city: '位置信息',
              address: '',
              basePrice: 0,
              rating: 0,
              reviewCount: 0,
              imageUrl: 'https://images.unsplash.com/photo-1566073771259-6a8506099945?w=400&h=300&fit=crop',
              isHot: false,
              amenities: [],
              description: '暂无描述'
            }
          }
          
          return {
            ...favorite,
            property
          }
        } catch (error) {
          console.error(`加载房产 ${favorite.propertyId} 详情失败:`, error)
          return {
            ...favorite,
            property: {
              id: favorite.propertyId,
              title: '民宿房源',
              city: '位置信息',
              address: '',
              basePrice: 0,
              rating: 0,
              reviewCount: 0,
              imageUrl: 'https://images.unsplash.com/photo-1566073771259-6a8506099945?w=400&h=300&fit=crop',
              isHot: false,
              amenities: [],
              description: '暂无描述'
            }
          }
        }
      })
    )
    
    favorites.value = favoritesWithDetails
    console.log('最终收藏数据:', favorites.value)
  } catch (error) {
    console.error('加载收藏列表失败:', error)
    ElMessage.error('加载收藏列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 初始化
onMounted(() => {
  loadFavorites()
})

// 处理排序
const handleSort = () => {
  // 排序逻辑已在computed中处理
}

// 移除收藏
const removeFavorite = async (propertyId) => {
  try {
    await ElMessageBox.confirm('确定要移除这个收藏吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    loading.value = true
    await cancelFavorite(propertyId)
    
    // 从列表中移除
    const index = favorites.value.findIndex(f => f.propertyId === propertyId)
    if (index > -1) {
      favorites.value.splice(index, 1)
    }
    
    ElMessage.success('已移除收藏')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除收藏失败:', error)
      ElMessage.error('移除收藏失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 清空所有收藏
const clearAllFavorites = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有收藏吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    loading.value = true
    
    // 逐个取消收藏
    const promises = favorites.value.map(favorite => 
      cancelFavorite(favorite.propertyId)
    )
    
    await Promise.all(promises)
    favorites.value = []
    ElMessage.success('已清空所有收藏')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空收藏失败:', error)
      ElMessage.error('清空收藏失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}
</script>

<style scoped>
.favorites-page {
  min-height: 100vh;
  background: #f8f9fa;
  padding: 20px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h1 {
  font-size: 2rem;
  color: #333;
  margin: 0;
}

.favorites-content {
  space-y: 20px;
}

.favorites-list {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.view-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  border-bottom: 1px solid #eee;
}

.favorites-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 30px;
  padding: 30px;
}

.favorite-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
}

.favorite-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.property-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.property-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.property-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  background: #ff4757;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.favorite-actions {
  position: absolute;
  top: 10px;
  left: 10px;
}

.remove-btn {
  background: rgba(255, 255, 255, 0.9);
  border: none;
  color: #ff4757;
}

.remove-btn:hover {
  background: white;
  color: #ff4757;
}

.property-info {
  padding: 20px;
}

.property-info h3 {
  font-size: 1.2rem;
  color: #333;
  margin-bottom: 8px;
}

.property-location {
  color: #666;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 0.9rem;
}

.property-rating {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.review-count {
  color: #666;
  font-size: 0.9rem;
}

.property-amenities {
  margin-bottom: 15px;
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.property-price {
  display: flex;
  align-items: baseline;
  gap: 5px;
  margin-bottom: 10px;
}

.price {
  font-size: 1.5rem;
  font-weight: bold;
  color: #ff4757;
}

.unit {
  color: #666;
  font-size: 0.9rem;
}

.favorite-time {
  color: #999;
  font-size: 0.8rem;
}

.favorites-list-view {
  padding: 30px;
}

.favorite-list-item {
  display: flex;
  gap: 20px;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 12px;
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.favorite-list-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #409eff;
}

.favorite-list-item .property-image {
  width: 200px;
  height: 150px;
  flex-shrink: 0;
}

.property-content {
  flex: 1;
}

.property-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.property-header h3 {
  font-size: 1.3rem;
  color: #333;
  margin: 0;
}

.property-description {
  color: #666;
  margin: 10px 0;
  line-height: 1.5;
}

.property-price-section {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: space-between;
  min-width: 150px;
}

.empty-state {
  background: white;
  border-radius: 12px;
  padding: 60px 30px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 20px;
    align-items: stretch;
  }
  
  .view-controls {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .favorites-grid {
    grid-template-columns: 1fr;
    padding: 20px;
  }
  
  .favorite-list-item {
    flex-direction: column;
  }
  
  .favorite-list-item .property-image {
    width: 100%;
    height: 200px;
  }
  
  .property-price-section {
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    margin-top: 15px;
  }
}
</style>


